//
//  ChoiceCurrentPositionViewController.m
//  mcrmSAAS
//
//  Created by wjxfhxy on 14-6-18.
//  Copyright (c) 2014年 GuangZhouXuanWu. All rights reserved.
//

#import "ChoiceCurrentPositionViewController.h"

#import "CustomAnnotation.h"

#import "LoadAddressPopupView.h"

NSString *const ChoiceCurrentPositionViewControllerChoicPositionParamKey = @"ChoiceCurrentPositionViewControllerChoicPositionParamKey";

NSString *const ChoiceCurrentPositionViewControllerDefaultPositionParamKey = @"ChoiceCurrentPositionViewControllerDefaultPositionParamKey";

@interface ChoiceCurrentPositionViewController ()<BMKMapViewDelegate,XLGPositioningHelperDelegate>
{
//    BMKUserLocation *_location;
    
    BMKMapView *_mapView;
    
    LoadAddressPopupView *_loadAddressPopupView;
    
    UIImageView *_pinImageView;
    
    CLLocationCoordinate2D _coor;
    NSString *_address;
    
    //默认完整的地址信息
    BOOL _loadDefualtPosition;
    
    //地址信息不全
    BOOL _fixErrorPostion;
    
    //没有任何地址信息
    BOOL _initCurrentPosition;
    
    //界面初始化时候，定位服务是否可用
    BOOL _networkVisiable;
    
    //反查不到地址，（不是没有开启地位或没有网络）
    BOOL _errorAddressLocation;
    
    void(^_fixErrorPostionFun)();
    
    void(^_initCurrentPositionFun)();
    
    XMSTimerBlock *_timer;
}

@end

@implementation ChoiceCurrentPositionViewController

- (void)viewDidLoad
{
    [self setBackNavigateItemTitle:@"位置信息" rightItemText:@"确定"];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    _mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
    _mapView.zoomLevel = 15;
    _mapView.delegate = self;
    
    [self.view addSubview:_mapView];
    
    [self addMainThreadObserverWithDictionarySelector:@{
                            UIApplicationWillEnterForegroundNotification:@"observerUIApplicationWillEnterForegroundNotification:",
                            UIApplicationDidEnterBackgroundNotification:@"observerUIApplicationDidEnterBackgroundNotification:",
                            XMSNetWorkReachabilityStatusChangedNotification:@"observerXMSNetWorkReachabilityStatusChangedNotification:"}];
    
    [XUINavigationController enableSwipeToLeftViewController:NO];
    
    _networkVisiable = YES;
    
    _errorAddressLocation = NO;
}


-(void)viewControllerDidMoveAppear
{
    [super viewControllerDidMoveAppear];
    
    if(self.param[ChoiceCurrentPositionViewControllerDefaultPositionParamKey] != nil)
    {
        NSString *s = self.param[ChoiceCurrentPositionViewControllerDefaultPositionParamKey];
        NSArray *ar = [s componentsSeparatedByString:@";"];
        if(ar.count >= 3)
        {
            _coor = CLLocationCoordinate2DMake([ar[0] floatValue], [ar[1] floatValue]);
            _address = ar[2];
            
            if(_address.length > 0 && _coor.latitude > 0 && _coor.longitude > 0)
            {
                _loadDefualtPosition = YES;
                
                //百度地图bug，不延迟，冒泡会坐标错误
//                DispatchMainThreadSyncAfterDelay(0.7, ^
//                {
//                    [_mapView setCenterCoordinate:_coor animated:NO];
//                });
                
                [_mapView setCenterCoordinate:_coor animated:NO];
            }
            else
            {
                _fixErrorPostion = YES;
                
                _fixErrorPostionFun = ^
                {
                    _timer = [[XMSTimerBlock alloc] initScheduledTimerWithTimeInterval:15 repeats:NO block:^(XMSTimerBlock *timer)
                    {
                        _fixErrorPostion = NO;
                        
                        [_timer invalidate];
                        
                        [super endProgressViewPanel];
                        
                        [XLGPositioningHelper cancelReceiver:self];
                        
                        [UIAlertView showInfoMsg:@"地址无法显示"];
                    }];
                    
                    if(_address.length > 0 && (_coor.latitude <= 0 || _coor.longitude <= 0))
                    {
                        [super beginProgressViewPanel:@"定位中，请稍候"];
                        
                        [XLGPositioningHelper getCoordWithReceiver:self addr:_address city:_address completion:NULL];
                    }
                    else if(_address.length <= 0 && _coor.latitude > 0 && _coor.longitude > 0)
                    {
                        [super beginProgressViewPanel:@"定位中，请稍候"];
                        
                        [XLGPositioningHelper getAddrWithReceiver:self coordinate:_coor completion:NULL];
                    }
                };
                
                if([XLGPositioningHelper locationServiceVisible] == NO)
                {
 //                   _locationVisiable = NO;
                }
                else if([XLGPositioningHelper isNetworkReachable] == NO)
                {
                    _networkVisiable = NO;
                    
                    [UIAlertView showErrorMsg:XUIViewControllerBusinessDataRequestNetWorkOfflineTip];
                    return;
                }
                
                _fixErrorPostionFun();
            }
        }
    }
    else
    {
        _initCurrentPosition = YES;
        
        _initCurrentPositionFun = ^
        {
            [super beginProgressViewPanel:@"定位中……"];
            
            [XLGPositioningHelper getCoordWithReceiver:self completion:NULL];
            self.rightBarButtonItem.enabled = NO;
        };
        
        if([XLGPositioningHelper locationServiceVisible] == NO)
        {
//            _locationVisiable = NO;
        }
        else if([XLGPositioningHelper isNetworkReachable] == NO)
        {
            _networkVisiable = NO;
            
            [UIAlertView showErrorMsg:XUIViewControllerBusinessDataRequestNetWorkOfflineTip];
            return;
        }
        
        _initCurrentPositionFun();
    }
}

-(void)viewControllerWillMoveDealloc
{
    [super viewControllerWillMoveDealloc];
    
    [self removeObserver];
    
    [super endProgressViewPanel];
    
    _initCurrentPositionFun = NULL;
    
    _fixErrorPostionFun = NULL;
    
    [_timer invalidate];
    _timer = nil;
    
    _mapView.delegate = nil;
    
    [XLGPositioningHelper cancelReceiver:self];
    
    [XUINavigationController enableSwipeToLeftViewController:YES];
}

-(void)clickedRightBarButton:(id)sender
{
    XUIViewControllerSwitchParam *p = [XUIViewControllerSwitchParam new];
    p.param[ChoiceCurrentPositionViewControllerChoicPositionParamKey] = [NSString stringWithFormat:@"%f;%f;%@",_coor.latitude,_coor.longitude,_address.length>0?_address:@""];
    [XUINavigationController popWithSwitchParam:p];
}

#pragma mark --
#pragma mark -- bmkmapview delegate

- (void)mapView:(BMKMapView *)mapView regionWillChangeAnimated:(BOOL)animated
{
    [XLGPositioningHelper cancelReceiver:self];
    
    [_loadAddressPopupView dismiss];
    _loadAddressPopupView = nil;
}

- (void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
//    if(_errorAddressLocation == NO)
//    {
//        if(_loadDefualtPosition == NO)
//        {
//            if(_locationVisiable == NO)
//                return;
//            
//            if([XLGPositioningHelper locationServiceVisible] == NO)
//            {
//                _locationVisiable = NO;
//                return;
//            }
//            else if([XLGPositioningHelper isNetworkReachable] == NO)
//            {
//                _locationVisiable = NO;
//                return;
//            }
//        }
//    }
    
    if(_loadDefualtPosition == YES)
    {
        _loadDefualtPosition = NO;
        
        CGPoint p = [mapView convertCoordinate:_coor toPointToView:_mapView];
        p.y -= 10;
        _pinImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"img_choiceposition_red.png"]];
        _pinImageView.center = p;
        [_mapView addSubview:_pinImageView];
        
        _loadAddressPopupView = [[LoadAddressPopupView alloc]initWithAnchorView:_pinImageView parnetView:_mapView];
        [_loadAddressPopupView show];
        if(_address.length > 0)
            [_loadAddressPopupView setAddress:_address];
        else
            [XLGPositioningHelper cancelReceiver:self];

        return;
    }
    
    if(_pinImageView == nil)
    {
         _pinImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"img_choiceposition_red.png"]];
        _pinImageView.center = CGPointMake(_mapView.width/2, _mapView.height/2-10);
        [_mapView addSubview:_pinImageView];
    }
    [_mapView bringSubviewToFront:_pinImageView];
    
    CGPoint p =_pinImageView.center;
    p.y += 10;
    
    _loadAddressPopupView = [[LoadAddressPopupView alloc]initWithAnchorView:_pinImageView parnetView:_mapView];
    [_loadAddressPopupView show];
    
    CLLocationCoordinate2D coor = [mapView convertPoint:p toCoordinateFromView:_mapView];
    _coor = coor;
    
    [XLGPositioningHelper getAddrWithReceiver:self coordinate:coor completion:NULL];
}

- (void)positioningHelperUpdateAddr:(id<XLGPositingReverseGeoCodeResult>)addr userInfo:(id)userInfo error:(NSError *)error
{
    [XLGPositioningHelper cancelReceiver:self];
    
    _initCurrentPosition = NO;
    
    if(_fixErrorPostion == NO)
    {
        if(error == nil)
        {
            _networkVisiable = YES;
            
            _errorAddressLocation = NO;
            
            _address = addr.address.length <= 0 ? @"" : addr.address;
    
            [_loadAddressPopupView setAddress:addr.address.length <= 0 ? @"未知地址" : addr.address];
            
            self.rightBarButtonItem.enabled = YES;
        }
        else
        {
            [_loadAddressPopupView dismiss];
            _loadAddressPopupView = nil;
            
            [UIAlertView showInfoMsg:@"地址无法显示"];
            
            self.rightBarButtonItem.enabled = NO;
        }
    }
    else
    {
        _fixErrorPostion = NO;
        
        [_timer invalidate];
        
        [super endProgressViewPanel];
        
        if(error == nil && addr.location.latitude > 0 && addr.location.longitude > 0)
        {
            _networkVisiable = YES;
            
            _errorAddressLocation = NO;
            
//            if(_coor.latitude <= 0 || _coor.longitude <= 0)
//                _coor = addr.location;
            
            if(_address.length <= 0)
                _address = addr.address.length <= 0 ? @"" : addr.address;
            
            _loadDefualtPosition = YES;
            
            self.rightBarButtonItem.enabled = NO;
            
//            DispatchMainThreadSyncAfterDelay(0.7, ^
//            {
//                [_mapView setCenterCoordinate:_coor animated:NO];
//            });
            [_mapView setCenterCoordinate:_coor animated:NO];
        }
        else
        {
            [_loadAddressPopupView dismiss];
            _loadAddressPopupView = nil;
            
            self.rightBarButtonItem.enabled = YES;
            
            [UIAlertView showInfoMsg:@"地址无法显示"];
        }
    }
}

- (void)positioningHelperUpdateCoord:(CLLocation *)location userInfo:(id)userInfo error:(NSError *)error
{
    if(_initCurrentPosition == YES)
    {
        [super endProgressViewPanel];
        
        if(error == nil)
        {
            _initCurrentPosition = NO;
            
            _networkVisiable = YES;
            
            _errorAddressLocation = NO;
            
            [XLGPositioningHelper cancelGetCoordWithReceiver:self];
            
            if(location.coordinate.latitude <=0 ||location.coordinate.longitude <=0)
            {
                [UIAlertView showInfoMsg:@"地址无法显示"];
                self.rightBarButtonItem.enabled = YES;
                return;
            }
            
            _mapView.centerCoordinate = location.coordinate;
            
            self.rightBarButtonItem.enabled = NO;
        }
        else
        {
            [_loadAddressPopupView dismiss];
            _loadAddressPopupView = nil;
            
            self.rightBarButtonItem.enabled = YES;
            
            if(error.code == XLGPositioningErrorSystemServiceDisable || error.code == XLGPositioningErrorAppServiceDisable)
                [UIAlertView showInfoMsg:RSWLocationServiceDisableTip];
            else
            {
                _errorAddressLocation = YES;
                [UIAlertView showInfoMsg:@"地址无法显示"];
            }
        }
    }
    else
    {
        _fixErrorPostion = NO;
        
        [_timer invalidate];
        
        [super endProgressViewPanel];
        
        if(error == nil && location.coordinate.latitude > 0 && location.coordinate.longitude > 0)
        {
            _networkVisiable = YES;
            
            _errorAddressLocation = NO;
            
            [XLGPositioningHelper cancelGetCoordWithReceiver:self];
            
            if(_coor.latitude <= 0 || _coor.longitude <= 0)
                _coor = location.coordinate;
            
            _loadDefualtPosition = YES;
            
            self.rightBarButtonItem.enabled = NO;
            
//            DispatchMainThreadSyncAfterDelay(0.7, ^
//            {
//                [_mapView setCenterCoordinate:_coor animated:NO];
//            });
            [_mapView setCenterCoordinate:_coor animated:NO];
        }
        else
        {
            [_loadAddressPopupView dismiss];
            _loadAddressPopupView = nil;
            
            self.rightBarButtonItem.enabled = YES;
            
            if(error.code == XLGPositioningErrorSystemServiceDisable || error.code == XLGPositioningErrorAppServiceDisable)
                [UIAlertView showInfoMsg:RSWLocationServiceDisableTip];
            else
            {
                _errorAddressLocation = YES;
                [UIAlertView showInfoMsg:@"地址无法显示"];
            }
        }
    }
}

#pragma mark --
#pragma mark -- observer

-(void)observerUIApplicationWillEnterForegroundNotification:(NSNotification*)noti
{
    if([XLGPositioningHelper isNetworkReachable] == YES)
    {
        _networkVisiable = YES;
        
        if(_initCurrentPosition == YES)
        {
            _initCurrentPositionFun();
        }
        else if(_fixErrorPostion == YES)
        {
            _fixErrorPostionFun();
        }
        else
        {
            [_loadAddressPopupView dismiss];
            _loadAddressPopupView = nil;
            
            //百度地图bug，必须延迟
//            DispatchMainThreadSyncAfterDelay(0.7, ^
//            {
//                [self mapView:_mapView regionDidChangeAnimated:NO];
//            });
            [self mapView:_mapView regionDidChangeAnimated:NO];
        }
    }
}

-(void)observerUIApplicationDidEnterBackgroundNotification:(NSNotification*)noti
{
    [_timer invalidate];
    
    [super endProgressViewPanel];
    
    [XLGPositioningHelper cancelReceiver:self];
}

- (void)observerXMSNetWorkReachabilityStatusChangedNotification:(NSNotification *)noti
{
    XMSNetWorkReachability *reach = [noti object];
    if (reach != [XMSNetWorkReachability reachability])
        return;
    
    XMSNetWorkReachabilityType netstatus = [reach currentReachabilityStatus];
    if (XMSNetWorkReachabilityTypeNotReachable == netstatus)
    {
        _networkVisiable = NO;
        
        [XLGPositioningHelper cancelReceiver:self];
    }
    else
    {
        [_loadAddressPopupView dismiss];
        _loadAddressPopupView = nil;
        
        [self mapView:_mapView regionDidChangeAnimated:NO];
    }
}

@end
